<?php

namespace upload;

use aliyun\AliyunOss;
use think\facade\Filesystem;
use think\File;

class ImgUpload
{
    /**
     * 图片上传至阿里云
     * @param File $file
     * @param string $folder
     * @param int $new_width
     * @param int $new_height
     * @param $percent
     * @return array
     */
    public static function imgUploadAliyun(File $file, string $folder, int $new_width, int $new_height, $percent): array
    {
        //数据验证
        validate(['imgFile' => [
            'fileSize' => 16388608,
            'fileExt' => 'jpg,jpeg,png,bmp,gif',
            'fileMime' => 'image/jpeg,image/png,image/gif', //这个一定要加上
        ]])->check(['imgFile' => $file]);
        //保存文件
        $savename = Filesystem::putFile('', $file);
        //获取文件完整路径
        $savename = Filesystem::path($savename);
        //图片压缩
        $ImgCompress = new ImgCompress($savename, $new_width, $new_height, $percent);
        $img = $ImgCompress->compressImg();
        //获取文件后缀名
        $suffix = pathinfo($savename)['extension'];
        //图片上传至阿里云
        $AliyunOss = new AliyunOss();
        $res = $AliyunOss->uploadFile($savename, $folder, '.' . $suffix);
        $file_size = @filesize($savename) / 1024;
        //文件授权777
        chmod($savename, 0777);
        unlink($savename);//删除文件
        return [
            'src' => $res['src'],
            'src_url' => $AliyunOss->getObjectUrl($res['src']),
            'width' => $img['width'],
            'height' => $img['height'],
            'file_size' => intval($file_size)
        ];
    }

    /**
     * 图片上传至阿里云
     * @param File $file
     * @param string $folder
     * @param int $new_width
     * @param int $new_height
     * @param $percent
     * @return array
     */
    public static function imgUpload(File $file, string $folder, int $new_width, int $new_height, $percent): array
    {
        //数据验证
        validate(['imgFile' => [
            'fileSize' => 16388608,
            'fileExt' => 'jpg,jpeg,png,bmp,gif',
            'fileMime' => 'image/jpeg,image/png,image/gif', //这个一定要加上
        ]])->check(['imgFile' => $file]);
        //保存文件
        $savename = Filesystem::putFile('', $file);
        //获取文件完整路径
        $savename = Filesystem::path($savename);
        //图片压缩
        $ImgCompress = new ImgCompress($savename, $new_width, $new_height, $percent);
        $img = $ImgCompress->compressImg();
        //获取文件后缀名
        $suffix = pathinfo($savename)['extension'];

        $fielName = \think\facade\Filesystem::disk('public')->putFile('upload',$file);

        $file_size = @filesize($savename) / 1024;
        return [
            'src' => $fielName,
            'src_url' => env('ApiImagesUrl').$fielName,
            'width' => $img['width'],
            'height' => $img['height'],
            'file_size' => intval($file_size)
        ];
    }
}